﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;

namespace ObjectModel.Excel
{
    public class WorkbookEvents
    {
        Workbook mWorkbook;

        public event EventHandler AfterSave;

        public WorkbookEvents(Workbook workbook)
        {
            mWorkbook = workbook;
            mWorkbook.BeforeSave += WorkbookBeforeSave;
        }

        void WorkbookBeforeSave(bool SaveAsUI, ref bool Cancel)
        {
            if (SaveAsUI)
            {
                Cancel = true;
                WorkbookSaveAs();
            }
            else
            {
                WorkbookSave();
                OnAfterSave();
            }
        }

        void WorkbookSave()
        {
            mWorkbook.BeforeSave -= WorkbookBeforeSave;
            mWorkbook.Save();
            mWorkbook.BeforeSave += WorkbookBeforeSave;
        }

        void WorkbookSaveAs()
        {
            Application app = mWorkbook.Application;

            FileDialog fd = app.FileDialog[MsoFileDialogType.msoFileDialogSaveAs];
            fd.InitialFileName = mWorkbook.FullName;
            if (fd.Show() == -1)
            {
                bool origDisplayAlertsSetting = app.DisplayAlerts;
                app.DisplayAlerts = false;
                fd.Execute(); // Raises BeforeSave event where SaveAsUI == false
                app.DisplayAlerts = origDisplayAlertsSetting;
            }
        }

        void OnAfterSave()
        {
            if (AfterSave != null)
                AfterSave(this, new EventArgs());
        }
    }
}
